package com.kakahair.plat.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.framework.controller.AjaxResult;
import com.kakahair.common.HttpResult;
import com.kakahair.common.controller.BaseController;
import com.kakahair.common.util.AjaxResponse;
import com.kakahair.common.util.HttpUtil;
import com.kakahair.common.util.KakahairConst;
import com.kakahair.common.util.Utility;
import com.kakahair.plat.entity.Sb;
import com.kakahair.plat.service.SbService;

import net.sf.json.JSONObject;

import java.io.IOException;
import java.io.PrintWriter;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.client.ClientProtocolException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Tiddar
 * @since 2018-05-07
 */
@Controller
@RequestMapping("/sb")
public class SbController extends BaseController {
	@Autowired
	SbService sbService;

	@ResponseBody
	@GetMapping("/list")
	public List<Sb> list() {
		return sbService.selectList(null);

	}

	@ResponseBody
	@PostMapping("/insert")
	public void insert(@RequestBody JSONObject data) {
		String content = data.getString("content");
		sbService.insert(new Sb().setContent(content));
	}

	@ResponseBody
	@GetMapping("/cnmwx")
	public AjaxResponse cnmwx(String code) throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException,
			ClientProtocolException, IOException {

		AjaxResponse response = AjaxResponse.instance();
		response.setData(getParam(KakahairConst.MP_APPID,KakahairConst.MP_SERCET,code));
		return response;
	}

	@ResponseBody
	@GetMapping("cnmcnm")
	/* 生成永久二维码 */
	public String getPerpetualQR() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, ClientProtocolException, IOException {

		// 获取数据的地址（微信提供）
		String url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token="
				+ ((Map) (cnmwx("").getData())).get("access_token");

		// 发送给微信服务器的数据
		String jsonStr = "{\"action_name\": \"QR_LIMIT_SCENE\", \"action_info\"：{\"scene\": {\"scene_name\": " + "xinzining"
				+ "}}}";

		// post请求得到返回数据（这里是封装过的，就是普通的java post请求）
		String response =	HttpUtil.sendPost(jsonStr, url);
		return response.toString();
	}
	  
	
	    @RequestMapping(value = "/wxsb")  
	    public void get(HttpServletRequest request, HttpServletResponse response) throws Exception {  
	  
	        logger.error("WechatController   ----   WechatController");  
	  
	        System.out.println("========WechatController========= ");  
	        logger.info("请求进来了...");  
	  
	        Enumeration pNames = request.getParameterNames();  
	        while (pNames.hasMoreElements()) {  
	            String name = (String) pNames.nextElement();  
	            String value = request.getParameter(name);  
	            // out.print(name + "=" + value);  
	  
	            String log = "name =" + name + "     value =" + value;  
	            logger.error(log);  
	        }  
	  
	        String signature = request.getParameter("signature");/// 微信加密签名  
	        String timestamp = request.getParameter("timestamp");/// 时间戳  
	        String nonce = request.getParameter("nonce"); /// 随机数  
	        String echostr = request.getParameter("echostr"); // 随机字符串  
	        PrintWriter out = response.getWriter();  
	  
	        if (Utility.checkSignature(signature, timestamp, nonce)) {  
	            out.print(echostr);  
	        }  
	        out.close();  
	        out = null;  
	  
	    }  
	  
	private Map getParam(String appid,String sercet,String code) throws IOException {
		Map<String, String> map = new HashMap<String, String>();
		String openidresult = "";
		map.put("appid", "wx6a0643aaa2cdc0a2");
		map.put("sercet", "11c930923da0dc43621f638e0127fa8f");
		String tokenresult = HttpUtil.httpsRequest(
				"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+sercet,
				"GET", null).toString();
		if (null != code) {
			openidresult = HttpUtil.httpsRequest(
					"https://api.weixin.qq.com/sns/jscode2session?appid=wx6a0643aaa2cdc0a2&secret=11c930923da0dc43621f638e0127fa8f&js_code="
							+ code + "&grant_type=authorization_code",
					"GET", null).toString();
		}
		JSONObject json = JSONObject.fromObject(tokenresult);
		System.out.println("response"+tokenresult);
		map.put("access_token", json.getString("access_token"));
		map.put("openid", openidresult);
		return map;
	}
}
